package com.heima.user.service.Imp;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojo.ApAuthor;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.AuthDTO;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.pojo.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.UserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImp extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements UserService {

    /**
     * 查询用户审核列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult getList(AuthDTO dto) {
        //1.校验参数
        dto.checkParam();
        //2.执行查询
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        //根据状态进行查询
        LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery();
        if (dto.getStatus() != null) {
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> iPage = this.page(page, wrapper);
        return new PageResponseResult(dto.getPage(),dto.getSize(),page.getTotal(),iPage.getRecords());
    }
    //注入mapper
    @Autowired
    private ApUserMapper apUserMapper;
    //远程调用
    @Autowired
    private WemediaFeign wemediaFeign;

    @GlobalTransactional
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //1.校验参数 判断id是否存在
        if (dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.校验当前参数对应的用户是否存在
        ApUserRealname apUserRealname = getById(dto.getId());
        if (apUserRealname == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"实名认证信息不存在！");
        }
        //3.判断当前状态是否是待审核状态
        if (!AdminConstants.WAIT_AUTH.equals(apUserRealname.getStatus())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"该用户的状态不是待审核状态！");
        }
        //根据实名认证的userid 获取用户信息
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        //校验数据
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"未发现关联的实名认证的用户信息！");
        }
        //TODO 使用用友校验身份信息及相关的数据

        //TODO 1.根据身份证正面照片使用OCR技术扫描出姓名 + 身份证号
        //TODO 2.根据姓名加身份证号 检查image是否为真实的自拍 不真实状态修改为2
        //TODO 3.使用活体检测接口 检测image 是否为真实自拍 score>85 (如果不真实 状态修改为2)
        //TODO 4.使用人脸检测接口 判断活体检测照片 和身份证是否一致 如果score>xx满足 (如果不真实 状态修改为2)


        //4.更新实名认证表中的状态
        apUserRealname.setStatus(status);
        apUserRealname.setReason(dto.getMassage());
        this.updateById(apUserRealname);
        //5.判断当前审核的状态是否是9
        if (AdminConstants.PASS_AUTH.equals(apUserRealname.getStatus())) {
            //开通自媒体账户
            WmUser wmUser = creatWemediaUser(apUser);
            //创建作者信息
            creatAuthor(wmUser,apUser);
        }
    /*    if (apUser.getId() == 5) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"演示异常");
        }*/
        return ResponseResult.okResult();
    }

    /**
     * 创建作者信息
     */
    @Autowired
    private ArticleFeign articleFeign;

    private void creatAuthor(WmUser wmUser,ApUser apUser) {
        //1.根据用户id查询作者信息
        ResponseResult<ApAuthor> result = articleFeign.findByUserId(apUser.getId());
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用失败！");
        }
        ApAuthor author = result.getData();

        //2.查看作者是否存在
        if (author != null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"作者存在！");
        }
        //3.作者不存在 创建
        author = new ApAuthor();
        author.setName(apUser.getName());
        author.setType(AdminConstants.AUTHOR_TYPE);
        author.setUserId(apUser.getId());
        author.setCreatedTime(new Date());
        author.setWmUserId(wmUser.getId());
        //4.远程调用创建作者信息
        articleFeign.save(author);
    }

    /**
     * 远程开通自媒体账户
     * @param apUser
     * @return
     */
    private WmUser creatWemediaUser(ApUser apUser) {
        //根据查询的用户信息查询是否存在信息
        ResponseResult<WmUser> responseResult = wemediaFeign.getByName(apUser.getName());
        if (!responseResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用失败！");
        }
        WmUser wmUser = responseResult.getData();
        //判断用户是否存在
        if (wmUser != null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户存在！");
        }
        //3.用户不存在 添加
        wmUser = new WmUser();
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9);
        wmUser.setType(0);
        wmUser.setLoginTime(new Date());
        wmUser.setCreatedTime(new Date());
        //远程调用添加
        ResponseResult<WmUser> save = wemediaFeign.save(wmUser);
        if (!save.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用失败！");
        }
        return save.getData();
    }
}
